package com.MyDemo.demo.interceptor;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

import javax.crypto.SecretKey;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.micrometer.common.lang.NonNull;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class TestInterceptor implements HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(TestInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String headerToken = request.getHeader("Authorization");

        SecretKey key = Keys.hmacShaKeyFor("itwt12341234asdfasdf12341234123412341234".getBytes(StandardCharsets.UTF_8));
        String jws = headerToken;
        /*
         * String subject =
         * Jwts.parser().verifyWith(key).build().parseSignedClaims(jws).getPayload().
         * getSubject();
         */
        try {
            Claims payload = Jwts.parser().verifyWith(key).build().parseSignedClaims(jws).getPayload();
            Object object = payload.get("username");
            if (Objects.isNull(object)) {
                throw new Exception("token is null");
            }
            logger.info("=============================================");
            logger.info("login user is :" + String.valueOf(object));
            logger.info("=============================================");
        } catch (Exception e) {
            logger.info("=============================================");
            logger.info("失败");
            logger.info("=============================================");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("{\"error\": \"Invalid token\"}");
            return false;
        }

        return true;
    }

}
